package com.java.controller;


import com.alibaba.fastjson.JSON;
import com.java.domain.Goods;
import com.java.service.GoodsService;
import com.java.service.impl.GoodServiceImpl;
import com.java.utils.DateUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(value = "/goods/*")
public class GoodsServlet extends BaseServlet {
    private GoodsService gs = new GoodServiceImpl();
    public void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Goods> goodsList = gs.getAllGoods();
        request.setAttribute("goodsList",goodsList);
        request.getRequestDispatcher("../index.jsp").forward(request,response);
    }
    public void querySingleGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int gid = Integer.parseInt(request.getParameter("gid"));
        Goods goods = gs.getSingleGoods(gid);
        request.setAttribute("goods",goods);
        request.getRequestDispatcher("../details.jsp").forward(request,response);
    }

    public void showGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");

        //获取全部商品信息
        int page = Integer.parseInt(request.getParameter("page"));
        int rows = Integer.parseInt(request.getParameter("limit"));
        List<Goods> goodsList = gs.getGoodsPageList(page,rows);

        Integer goodsCount = gs.getGoodsCount();

        //使用map集合传递数据
        Map<String, Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",goodsCount);
        map.put("data",goodsList);

        PrintWriter out = response.getWriter();
        String json = JSON.toJSONString(map);

        out.write(json);
        out.flush();
        out.close();
    }

    public void delGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int gid = Integer.parseInt(request.getParameter("gid"));
        PrintWriter out = response.getWriter();

        out.println(gs.delGoods(gid)?1:0);
    }

    public void updateGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Goods goods = new Goods();

        try {
            BeanUtils.populate(goods,request.getParameterMap());
            PrintWriter out = response.getWriter();
            out.println(gs.updateGoods(goods)?1:0);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public void addGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Goods goods = new Goods();
        try {
            BeanUtils.populate(goods,request.getParameterMap());
            PrintWriter out = response.getWriter();
            out.println(gs.addGoods(goods)?1:0);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public void goodsLike(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");

        String gname = request.getParameter("gname");
        String lowernum = request.getParameter("lowernum");
        String uppernum = request.getParameter("uppernum");

        // 继续接收分页数据
        int page = Integer.parseInt(request.getParameter("page"));
        int rows = Integer.parseInt(request.getParameter("limit"));


        List<Goods> goodsList = gs.goodsLike(gname, lowernum, uppernum,page,rows);

        Integer searchCount = gs.getSearchCount();//一定要在goodsLike()方法后调用

        //使用map集合传递数据
        Map<String, Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","错误");
        map.put("count",searchCount);
        map.put("data",goodsList);



        PrintWriter out = response.getWriter();
        String json = JSON.toJSONString(map);

        out.write(json);
        out.flush();
        out.close();
    }

    public void delAll(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String ids = request.getParameter("ids");

        PrintWriter out = response.getWriter();

        out.println(gs.delAll(ids)?1:0);

    }

    public void uploadImg(HttpServletRequest request,HttpServletResponse response) throws IOException {
        DiskFileItemFactory dff = new  DiskFileItemFactory();
        String path = request.getServletContext().getRealPath("/res/static/img");
        //String path = request.getContextPath()+"/res/static/img";
        System.out.println(path);

        // 设置文件上传时的缓存空间
        dff.setRepository(new File(path));
        // 缓存大小，以字节为单位
        dff.setSizeThreshold(4096);

        // 用上传工具实现接收表单数据
        ServletFileUpload sfu = new ServletFileUpload(dff);
        sfu.setHeaderEncoding("utf-8");

        // 一次性将所有表单元素（FileItem）封装到集合当中
        try {
            List<FileItem> items = sfu.parseRequest(request);

            FileItem fileItem = items.get(0);
            String oldName = fileItem.getName();

            String suffix = oldName.substring(oldName.lastIndexOf("."));
            String newName = DateUtils.getNewDateName()+suffix;
            System.out.println(newName);
            fileItem.write(new File(path,newName));

            //使用map集合传递数据
            Map<String, Object> map = new HashMap<>();
            map.put("code",0);
            map.put("msg","");
            map.put("data","src:"+newName);

            PrintWriter out = response.getWriter();
            String json = JSON.toJSONString(map);

            out.write(json);
            out.flush();
            out.close();


        } catch (Exception e) {
            e.printStackTrace();
        }


    }



}
